import json
from jc.jc_ci import *


class CiDynamorio(Ci):
    def run(self):
        fp = os.path.abspath(sys.argv[0])
        if fp.lower().endswith('.py'):
            fp = fp[0:-2] + 'sh'
        print(f'\nscript file: {fp}\n')
        if not os.path.exists(fp):
            return False

        env = os.environ
        path = 'c:/_jc/apps/git/Git-2.44.0-64.bit/mingw64/bin;' \
               'c:/_jc/apps/git/Git-2.44.0-64.bit/usr/local/bin;' \
               'c:/_jc/apps/git/Git-2.44.0-64.bit/usr/bin;' \
               'c:/_jc/apps/git/Git-2.44.0-64.bit/bin;'
        path += env['PATH']
        env['PATH'] = path
        # print(path)

        ############################################
        # building
        ############################################
        cmd = ['sh',
               to_shell_arg(fp),
               to_shell_arg(['--arch-config=', self.arch_config.name]),
               to_shell_arg(['--debug-config=', self.debug_config.name]),
               to_shell_arg(['-g', self.generator]),
               to_shell_arg(['-w', self.workspace_dir]),
               to_shell_arg(['-b', self.build_workspace_dir]),
               to_shell_arg(['-d', self.deploy_workspace_dir]),
               ]
        cmd += self.to_shell_clean_dirs()
        if self.arch_config == ArchConfigEnum.X64:
            cmd.append('-x')
        if self.test_clean_mode:
            cmd.append('-t')
        print('\ncmd: {}\n'.format(" ".join(cmd)))
        # exit(0)
        build_result = self.run_imp(cmd, env=env)
        # print(build_result)

        ############################################
        # running
        ############################################
        bit_string = '32' if ArchConfigEnum.WIN32 == self.arch_config else '64'
        cmd = [
            '{}/bin{}/drrun'.format(self.deploy_workspace_dir, bit_string), '-h']
        print('\ncmd: {}\n'.format(" ".join(cmd)))
        run_result = self.run_imp(cmd, env=env)
        # print(run_result)

        return [build_result, run_result]


def main():
    parser = CiDynamorio.parse('dynamorio')
    args = parser.parse_args()
    print(f'args: {args}\n')

    ci = CiDynamorio(args.arch_config,
                     args.debug_config,
                     args.generator,
                     args.build_root_dir,
                     args.deploy_root_dir,
                     args.clean_mode,
                     args.test_clean_mode)
    print(f'ci: {ci.__str__()}\n')
    if not ci.vaild:
        return
    rusults = ci.run()
    for r in rusults:
        print(r)


if __name__ == '__main__':
    main()
